package cn.com.zero.file.service.impl;

import cn.com.zero.file.config.properties.FileUploadProperties;
import cn.com.zero.file.service.IFileService;
import cn.com.zero.file.util.FileUtil;
import cn.com.zero.file.vo.FileInfo;
import cn.hutool.core.codec.Base64;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author liuxh
 * @version 1.0.0
 * @Description 本地文件服务实现类
 * @createTime 2022/9/14
 */
public class LocalFileServiceImpl implements IFileService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private String localFilePath;

    private FileUploadProperties fileUploadProperties;

    public LocalFileServiceImpl(String localFilePath, FileUploadProperties fileUploadProperties) {
        this.localFilePath = localFilePath;
        this.fileUploadProperties = fileUploadProperties;
    }

    @Override
    public FileInfo upload(MultipartFile file, String relativePath) {
        try {
            FileInfo fileInfo = FileUtil.getFileInfo(file, relativePath);
            String extension = fileInfo.getExtension();
            if (!FileUtil.isAllowedExtension(extension, fileUploadProperties.getAllowedExtension())) {
                throw new RuntimeException("上传文件失败，不允许上传文件类型为[" + extension + "]的文件！");
            }
            String path = fileInfo.getRelativeFilePath();
            Path pathTemp = Paths.get(this.localFilePath).toAbsolutePath().normalize();
            Path targetLocation = pathTemp.resolve(path);
            File targetFile = targetLocation.toFile();
            if (targetFile.exists()) {
                return fileInfo;
            }
            if (!targetFile.getParentFile().exists()) {
                File parentFile = targetFile.getParentFile();
                Files.createDirectories(parentFile.toPath());
            }

            file.transferTo(targetFile);
            return fileInfo;
        } catch (Exception e) {
            throw new RuntimeException("文件上传未知异常", e);
        }
    }

    @Override
    public FileInfo upload(MultipartFile file, String bucketName, String relativePath) {
        return upload(file, relativePath);
    }

    @Override
    public FileInfo uploadImage(MultipartFile file, String bucketName, String relativePath, Integer width, Integer height) {
        String extension = FileUtil.getExtension(file);
        if (!FileUtil.isAllowedExtension(extension, fileUploadProperties.getImageExtension())) {
            throw new RuntimeException("上传图片失败，不允许上传文件类型为[" + extension + "]的文件！");
        }
        MultipartFile multipartFile = FileUtil.compressImg(file, width, height);
        return upload(multipartFile, relativePath);
    }

    @Override
    public void delete(String relativeFilePath) {
        Path pathTemp = Paths.get(this.localFilePath).toAbsolutePath().normalize();
        Path targetLocation = pathTemp.resolve(relativeFilePath);
        File file = targetLocation.toFile();
        if (file.exists()) {
            boolean flag = file.delete();

            if (flag) {
                File[] files = file.getParentFile().listFiles();
                if (files == null || files.length == 0) {
                    file.getParentFile().delete();
                }
            }
        }
    }

    @Override
    public void delete(String bucketName, String relativeFilePath) {
        delete(relativeFilePath);
    }

    @Override
    public Boolean isExist(String relativeFilePath) {
        Path pathTemp = Paths.get(this.localFilePath).toAbsolutePath().normalize();
        Path targetLocation = pathTemp.resolve(relativeFilePath);
        File targetFile = targetLocation.toFile();
        return targetFile.exists();
    }

    @Override
    public Boolean isExist(String bucketName, String relativeFilePath) {
        return isExist(relativeFilePath);
    }

    @Override
    public Resource downloadFile(String bucketName, String relativeFilePath) {
        Preconditions.checkArgument(StringUtils.hasLength(relativeFilePath));
        try {
            Path pathTemp = Paths.get(this.localFilePath).toAbsolutePath().normalize();
            Path targetLocation = pathTemp.resolve(relativeFilePath);
            Resource resource = new UrlResource(targetLocation.toUri());
            if (resource.exists()) {
                return resource;
            } else {
                log.error("【本地文件服务】没有发现文件{}", relativeFilePath);
                throw new RuntimeException("没有发现文件!");
            }
        } catch (MalformedURLException e) {
            log.error("【本地文件服务】下载文件{}发生异常,", relativeFilePath, e);
            throw new RuntimeException("下载文件发生异常!", e);
        }
    }

    @Override
    public String downloadFileToBase64(String bucketName, String relativeFilePath) {
        Preconditions.checkArgument(StringUtils.hasLength(relativeFilePath));
        Path pathTemp = Paths.get(this.localFilePath).toAbsolutePath().normalize();
        Path targetLocation = pathTemp.resolve(relativeFilePath);
        File file = targetLocation.toFile();
        if (file.exists()) {
            return Base64.encode(file);
        } else {
            log.error("【本地文件服务】没有发现文件{}", relativeFilePath);
            throw new RuntimeException("没有发现文件!");
        }
    }

}
